package rpc_netty.NacosUtils;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

//将与nacos有关的函数集成到这个类中
public class NacosUtil {
    private static final Logger logger= LoggerFactory.getLogger(NacosUtil.class);
    private static final NamingService namingService;
    private static final Set<String> serviceNames=new HashSet<>();
    private static InetSocketAddress address;

    //nacos服务中心的地址
    private static final String NACOS_SERVER_ADDR="localhost:8848";
    private static ConfigService configService;

    static {
        try {
            configService = NacosFactory.createConfigService(NACOS_SERVER_ADDR);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        namingService=getNacosNamingService();
    }

    public static NamingService getNacosNamingService(){
        try {
            return NamingFactory.createNamingService(NACOS_SERVER_ADDR);
        } catch (NacosException e) {
            logger.error("error when connecting to the nacos",e);
            e.printStackTrace();
        }
        return null;
    }

    public static void registerService(String serviceName,InetSocketAddress address){
        try {
            namingService.registerInstance(serviceName,address.getHostName(), address.getPort());
            NacosUtil.address=address;
            serviceNames.add(serviceName);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    public static List<Instance> getAllInstances(String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }

    //根据当前服务的地址，和已经注册过的服务名称，调用nacos api进行服务注销
    public static void clearRegistry()  {
        if (!serviceNames.isEmpty()&&address!=null){
            String hostName = address.getHostName();
            int port = address.getPort();
            Iterator<String> iterator = serviceNames.iterator();
            while (iterator.hasNext()){
                String name = iterator.next();
                try {
                    namingService.deregisterInstance(name,hostName,port);
                    System.out.println(name);
                    System.out.println(hostName);
                    configService.removeConfig(name,hostName+":"+port);
                } catch (NacosException e) {
                    logger.error("error when deregister the service");
                    e.printStackTrace();
                }
            }
        }
    }

}
